# -*- coding: utf-8 -*-
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
# odoo17
# QQ:35350428
# 邮件:35350428@qq.com
# 手机：13584935775
# 作者：'Amos'
# 公司网址： www.xodoo.cn
# Copyright 昆山一百计算机有限公司
# 日期：2023-09-16
# &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

import os
import odoo
from odoo import http, _
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from jinja2 import Environment, FileSystemLoader
import logging
from datetime import datetime, timedelta
from odoo import api, fields, models

_logger = logging.getLogger(__name__)
from odoo.http import request
import json
import requests
import ast
from lxml import etree
from lxml.etree import LxmlError
from lxml.builder import E
from odoo.osv import expression

# TODO(amos): 加载模板
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
folder_path = BASE_DIR + "/static/templates"  # 相对文件路径
templateLoader = FileSystemLoader(searchpath=folder_path)
env = Environment(loader=templateLoader)
# TODO(amos): 去空格
env.trim_blocks = True
env.lstrip_blocks = True
env.cache_size = 5000  # 默认缓存模板数量
#::::定义全局变量
env.globals.update({
    'layout': 'false',  # 模板出现class_bg，默认模板
    'layout_nav_fixed': 'true',  # 固定侧导航
    'layout_header_fixed': 'true',  # 固定导航条
    'layout_header_color': 'bg-white',  # 导航背景
    'layout_sidenav_color': 'bg-white',  # 侧导航背景
    'layout_footer_color': 'bg-white',  # 页脚背景
})

# TODO(amos): 提供更多格式化方法
from . import jinja_filters

env.filters['date_format'] = jinja_filters.date_format
# env.filters['reverse'] = tools.jinja_filters.reverse_filter
# env.filters['section_filter'] = tools.jinja_filters.section_filter
# env.filters['date_filter'] = tools.jinja_filters.date_filter
# env.filters['decode'] = tools.jinja_filters.decode
# env.filters['split'] = tools.jinja_filters.split
# env.filters['list_split'] = tools.jinja_filters.list_split
from odoo.addons.portal.controllers.web import Home


def get_menu_solution(cr):
    """
    解决方案菜单
    :param cr:
    :return:
    """
    cr.execute(
        "SELECT id, name,click FROM public.solution where active='True' order by sequence asc,id desc  limit 10 ")
    row_values = cr.fetchall()
    return row_values


def get_solution(cr, id):
    """
    解决方案详细
    :param cr:
    :return:
    """
    cr.execute(
        "SELECT id, name, html,create_date,user_id,click FROM public.solution where active='True' and id=%s order by sequence asc,id desc  limit 10 " % id)
    row_values = cr.fetchall()
    return row_values


class Website(Home):

    def __init__(self):
        self.sessions = {}

    # 默认网站
    @http.route(['/<string:lang>/index', '/index', '/'], type='http', auth="public", website=True, sitemap=True)
    def index(self, lang="zh_CN", **kw):
        """
        数据看板
        :param kw:
        :return:
        """
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env
        values = {}
        values['menu_solution'] = get_menu_solution(cr)  # 解决方案

        csrf_token = request.csrf_token()
        values['csrf_token'] = csrf_token

        # 获取地址显示计划页面
        environ = request.httprequest.headers.environ
        HTTP_HOST = environ.get("HTTP_HOST")
        if HTTP_HOST == 'www.xodoo.cn':
            return request.redirect('/mall')



        template = env.get_template('%s/index.html' % lang)
        html = template.render(object=values)
        return html

    # 解决方案
    @http.route(['/odoo/solution/<int:id>'], type='http', auth="public", website=True, sitemap=True)
    def odoo_solution(self, id, **kw):
        """
        解决方案
        :param kw:
        :return:
        """
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env
        values = {}
        values['menu_solution'] = get_menu_solution(cr)  # 解决方案

        solution = pool['solution'].sudo().browse(id)  # 解决方案详细
        values['solution'] = solution
        solution.sudo().write({'click': solution.click + 1})
        # :::上一条
        Previous = pool['solution'].sudo().search([('id', '>', id)], order="sequence, id desc", limit=1)
        values['Previous'] = Previous
        # :::下一条
        Next = pool['solution'].sudo().search([('id', '<', id)], order="sequence, id desc", limit=1)
        values['Next'] = Next

        # :::全部关健字
        All_Tag = pool['solution.tag'].sudo().search([], order="id desc", limit=20)
        values['All_Tag'] = All_Tag

        try:
            template = env.get_template('zh_CN/solution.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    # 关于我们
    @http.route(['/about'], type='http', auth="public", website=True, sitemap=True)
    def about(self, **kw):
        """
        关于我们
        :param kw:
        :return:
        """
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env

        values = {}
        values['menu_solution'] = get_menu_solution(cr)  # 解决方案

        try:
            template = env.get_template('zh_CN/about.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    # 联系我们
    @http.route(['/contact'], type='http', auth="public", website=True, sitemap=True)
    def contact(self, **kw):
        """
        联系我们
        :param kw:
        :return:
        """
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env

        values = {}
        values['menu_solution'] = get_menu_solution(cr)  # 解决方案

        csrf_token = request.csrf_token()
        values['csrf_token'] = csrf_token

        try:
            template = env.get_template('zh_CN/contact.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    # 线索提交收取信息接口
    @http.route(['/contact/crm.lead'], type='json', auth="public", csrf=False, website=True, sitemap=True)
    def contact_crm_lead(self, **kw):
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env
        kw = json.loads(request.httprequest.data)
        if kw != {} and kw:
            contact_name = kw['name'] or ''
            subject = kw['subject'] or ''
            partner_name = kw['company'] or ''
            phone = kw['phone'] or ''
            email_from = kw['email_from'] or ''
            description = kw['description'] or ''
            # if request.env.user:
            #     partner = request.env.user.partner_id
            # else:
            #     partner = None

            values = {
                'contact_name': contact_name,
                'name': subject,
                'user_id': None,
                'partner_name': partner_name,
                'team_id': request.env['crm.team'].sudo().search([('name', '=', '网站')]).id,
                'partner_id': None,
                'email_from': email_from,
                'phone': phone,
                'description': description,
                'type': 'opportunity',
            }
            res = request.env['crm.lead'].sudo().create(values)
            # res.action_timer_start()

            # 发送短信
            sms = odoo.tools.config.get('sms', 'sms.tencent')  # 默认使用 sms.tencent
            values['sms'] = sms
            values['TemplateId'] = pool['csms.template'].get_temp_id('用户咨询', sms)  # 短信模板 用户咨询
            values['TemplateParamSet'] = [contact_name, partner_name, description + email_from, phone]  # 内容
            values['PhoneNumberSet'] = ["+8613584935775"]  # 接收短信多个使用逗号隔开
            request.env['base'].sudo().send_sms(values)

        data = {
            "errcode": 0,
            'errmsg': 'yes',
            "data": '',
            'message': '提交成功!'}
        return json.dumps(data)

    # 订阅接口
    @http.route(['/mailing'], type='json', auth="public", csrf=False, website=True, sitemap=True)
    def mailing(self, **kw):
        kw = json.loads(request.httprequest.data)
        message = '订阅成功!'
        if kw != {} and kw:
            name = kw['name'] or ''

            domain = [('name', '=', name)]
            rows_count = request.env['mailing'].sudo().search_count(domain)

            if rows_count == 0:
                request.env['mailing'].sudo().create({
                    'name': name,
                })
            else:
                message = '已存在！'

        data = {
            "errcode": 0,
            'errmsg': 'yes',
            "data": '',
            'message': message}
        return json.dumps(data)

    # 默认网站
    @http.route(['/download'], type='http', auth="public", website=True, sitemap=True)
    def download(self, **kw):
        """
        关于我们
        :param kw:
        :return:
        """
        cr, uid, context, pool = request.cr, odoo.SUPERUSER_ID, request.context, request.env

        values = {}
        values['menu_solution'] = get_menu_solution(cr)  # 解决方案

        try:
            template = env.get_template('zh_CN/download.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page1'], type='http', auth="public", website=True, sitemap=True)
    def page1(self, **kw):
        """
        客户关系管理 CRM
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page1.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page2'], type='http', auth="public", website=True, sitemap=True)
    def page2(self, **kw):
        """
        智能工厂 FFModels
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page2.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page3'], type='http', auth="public", website=True, sitemap=True)
    def page3(self, **kw):
        """
        Odoo桌面端框架
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page3.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page4'], type='http', auth="public", website=True, sitemap=True)
    def page4(self, **kw):
        """
        Flutter移动端框架
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page4.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page5'], type='http', auth="public", website=True, sitemap=True)
    def page5(self, **kw):
        """
        Vue 前端框架
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page5.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page6'], type='http', auth="public", website=True, sitemap=True)
    def page6(self, **kw):
        """
        IOT Thingsboard
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page6.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page7'], type='http', auth="public", website=True, sitemap=True)
    def page7(self, **kw):
        """
        API GRPC解决方案
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page7.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/page8'], type='http', auth="public", website=True, sitemap=True)
    def page8(self, **kw):
        """
        Net C#系列框架
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/page8.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    @http.route(['/product'], type='http', auth="public", website=True, sitemap=True)
    def product(self, **kw):
        """
        应用系统
        :param kw:
        :return:
        """

        values = {}

        try:
            template = env.get_template('zh_CN/product.html')
            html = template.render(object=values)
        except IOError:
            template = env.get_template('zh_CN/404.html')
            html = template.render(object=values)
        return html

    # 线索提交收取信息接口
    @http.route(['/crm_lead_create'], type='http', auth="public", csrf=False)
    def crm_lead_create(self, **kw):
        if kw != {} and kw:
            name = kw['name']
            mobile = kw['mobile']
            email = kw['email']
            help = kw['help']
            if request.env.user:
                partner = request.env.user.partner_id
            else:
                partner = None
            res = request.env['crm.lead'].sudo().create({
                'name': name + '的线索需求',
                'user_id': None,
                'team_id': request.env['crm.team'].sudo().search([('name', '=', '网站')]).id,
                'partner_id': partner.id,
                'email': email,
                'description': '手机号： %s\n 问题：' % mobile + help,
                'type': 'opportunity',
            })
            res.action_timer_start()
        return json.dumps({'error': 200, })
